<?php
namespace Common\Model;
use Common\Model\BaseModel;
/**
 * ModelName
 */
class GoodsCategoryModel extends BaseModel{
    // 自动验证
    protected $_validate=array(
        array('name','require','文章分类名必须',0,'',3), // 验证字段必填
    );

    // 自动完成
    protected $_auto=array(
        array('create_time','time',1,'function'), // 对date字段在新增的时候写入当前时间戳
    );

    /**
     * 添加文章分类
     */
    public function addData($data){
        // 对data数据进行验证
        if(!$data=$this->create($data)){
            // 验证不通过返回错误
            return false;
        }else{
            // 验证通过
            $result=$this->add($data);
            $map['id'] = $result;
            $cidList = array(0 => $result); 
            $this->addExpand(I('post.'),$map,$cidList);
            return $result;
        }
    }


    public function editData($map,$data){
        // 对data数据进行验证
        if(!$data=$this->create($data)){
            // 验证不通过返回错误
            return false;
        }else{
            if($data['id'] != $data['pid']){
                $pid = $this->getPids($data['pid'],'0');
                if(strpos($pid,$data['id'])){
                    return false;
                }else{
                    //如果上传了新主图，删除旧的主图
                    $oldPath = $this->where($map)->getField('pic_path');
                    if ($oldPath != $data['pic_path']) {
                        deleteFile($oldPath);
                    }
                    $result=$this
                        ->where(array($map))
                        ->save($data);
                    $expand = I('post.');
                    //拓展字段，设置只要有一个需要同步就递归获取所有子分类
                    if ($expand['config_synchronized'] == 1 || $expand['expand_synchronized'] == 1) {
                        $cidList = $this->getCids($map['id']);
                    }
                    //同步设置
                    if ($expand['config_synchronized'] == 1) {
                        $configMap['id'] = array('in', $cidList);
                        $update['seo'] = $data['seo'];
                        $update['attachment'] = $data['attachment'];
                        $update['album'] = $data['album'];
                        $update['content'] = $data['content'];
                        $update['address'] = $data['address'];
                        $this->where($configMap)->save($update);
                    }
                    //同步拓展字段
                    if ($expand['expand_synchronized'] == 1){
                        $expandMap['cid'] = array('in', $cidList);
                    } else {
                        $expandMap['cid'] = $map['id'];
                        $cidList = array(0 => $map['id']); 
                    }
                    $this->addExpand($expand, $expandMap,$cidList);
                    return true;
                }
            }else{
                return false;
            }
        }
    }

    public function addExpand($data,$map,$cids=array()){
        M('CategoryExpand')->where($map)->delete();
        $c_name = $data['c_name'];
        $e_name = $data['e_name'];
        $type = $data['type'];
        $value = $data['option'];
        $count = count($data['c_name']);
        for($i=0; $i<$count; $i++) {
            $expand['c_name'] = $data['c_name'][$i];
            $expand['e_name'] = $data['e_name'][$i];
            if(trim($expand['c_name']) == null || trim($expand['e_name']) == null) {
                continue;
            }
            $expand['type'] = $data['type'][$i];
            $expand['option'] = $data['option'][$i];
            foreach ($cids as $key => $value) {
                $expand['cid'] = $value;
                M('CategoryExpand')->add($expand);
            }
        }
    }

    public function getExpand($map){
        $list = M('CategoryExpand')->where($map)->select();
        if (count($list) != 0) {
            foreach ($list as $key => $value) {
                $data[$key]['c_name'] = $value['c_name'];
                $data[$key]['e_name'] = $value['e_name'];
                $data[$key]['type'] = $value['type'];
                $data[$key]['option'] = $value['option'];
                $data[$key]['cid'] = $value['cid'];
                $data[$key]['id'] = $value['id'];
            }
        }
        return $data;
    }

    /**
    * 递归获取所有父节点
    */
    public function getPids($pid,$str){
        $category = $this->where('id='.$pid)->find();
        if($category['pid'] == 0){
            return $str;
        }else{
            $str .= ','.$category['pid'];
            return $this->getPids($category['pid'],$str);
        }
    }

    /**
    * 递归获取所有子节点
    */
    public function getCids($id,$arr=array()){
        array_push($arr, $id);
        $children = $this->where('pid='.$id)->select();
        if(count($children) == 0){
            return $arr;
        }else{
            foreach ($children as $key => $value) {
                $arr = $this->getCids($value['id'], $arr);
            }
            return $arr;
        }
    }

    /**
     * 删除数据
     * @param   array   $map    where语句数组形式
     * @return  boolean         操作是否成功
     */
    public function deleteData($map){
        $path = $this->where($map)->getField('pic_path');
        $result = $this->where($map)->delete();
        if($result){
            M('CategoryExpand')->where('cid='.$map['id'])->delete();
            deleteFile($path);
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取全部菜单
     * @param  string $type tree获取树形结构 level获取层级结构
     * @return array        结构数据
     */
    public function getTreeData($type='tree',$order=''){
        // 判断是否需要排序
        if(empty($order)){
            $data=$this->select();
        }else{
            $data=$this->order('order_number is null,'.$order)->select();
        }
        // 获取树形或者结构数据
        if($type=='tree'){
            $data=\Org\Nx\Data::tree($data,'name','id','pid');
        }elseif($type="level"){
            $data=\Org\Nx\Data::channelLevel($data,0,'&nbsp;','id');
            foreach ($data as $k => $v) {
                $name = explode('@', $v['name']);
                $data[$k]['c_name'] = $name[0];
                $data[$k]['e_name'] = $name[1];
                foreach ($v['_data'] as $m => $n) {
                    $name = explode('@', $n['name']);
                    $data[$k]['_data'][$m]['c_name'] = $name[0];
                    $data[$k]['_data'][$m]['e_name'] = $name[1];
                }
            }
        }
        return $data;
    }

}
